package com.enation.app.javashop.core.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.enation.app.javashop.core.goods.model.dos.CategoryDO;
import com.enation.app.javashop.core.goods.model.dos.GoodsDO;
import com.enation.app.javashop.core.goods.service.CategoryManager;
import com.enation.app.javashop.core.goods.service.GoodsManager;
import com.enation.app.javashop.core.shop.model.dos.ShopCatDO;
import com.enation.app.javashop.core.shop.service.ShopCatManager;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 模板的读取类
 */
@Slf4j
public class GoodsDataListener extends AnalysisEventListener<GoodsImport> {
    /**
     * 每隔20条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 300;
    private List<GoodsImport> importList = new ArrayList<>();
    private List<GoodsImport> errorImportList = new ArrayList<>();
    private List<GoodsDO> updateGoods = new ArrayList<>();


    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private GoodsManager goodsManager;

    private CategoryManager categoryManager;

    private ShopCatManager shopCatManager;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param goodsManager
     */
    public GoodsDataListener(GoodsManager goodsManager,CategoryManager categoryManager,ShopCatManager shopCatManager) {
        this.goodsManager = goodsManager;
        this.categoryManager = categoryManager;
        this.shopCatManager = shopCatManager;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     *            one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(GoodsImport data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        importList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (importList.size() >= BATCH_COUNT) {
            updateData();
            // 存储完成清理 list
            importList.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        updateData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void updateData() {
        log.info("{}条数据，开始存储数据库！", importList.size());
        for (GoodsImport goodsImport : importList) {
            System.out.println(goodsImport);
            GoodsDO goodsDO=null;
            if (goodsImport.getGoodsId() != null) {
                goodsDO = goodsManager.getByGoodsId(goodsImport.getGoodsId());
            } else {
                goodsDO = goodsManager.getByUpGoodsId(goodsImport.getUpGoodsId());
            }
            if(goodsDO!=null){
                GoodsDO newGoodsDO = new GoodsDO();
                newGoodsDO.setGoodsId(goodsDO.getGoodsId());
                if(goodsImport.getCategoryName()!=null){
                    CategoryDO categoryDO= categoryManager.getByName(goodsImport.getCategoryName());
                    if(categoryDO==null){
                        continue;
                    }
                    newGoodsDO.setCategoryId(categoryDO.getCategoryId());
                }
                if(goodsImport.getShopCatName()!=null){
                    ShopCatDO shopCatDO = shopCatManager.getByName(goodsImport.getShopCatName(),goodsDO.getSellerId());
                    if(shopCatDO==null){
                        continue;
                    }
                    newGoodsDO.setShopCatId(shopCatDO.getShopCatId());
                }
                updateGoods.add(newGoodsDO);
            }else{
                errorImportList.add(goodsImport);
                continue;
            }
        }
        goodsManager.batchUpdateGoods(updateGoods);
        log.info("存储数据库成功！");
    }

}